﻿using AutoMapper;
using MediatR;
using Traceability.App.API.Application.Command.BasicTraceability;
using Traceability.App.Domain.Traceability;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructrue.Interface;

namespace Traceability.App.API.Application.Handler.BasicTraceability
{
    public class CreateBasicTraceabilityHandler : IRequestHandler<CreateBasicTraceabilityCommand, APIResult<int>>
    {
        private readonly IBaseRepository<BasicTraceabilityModel> basicRepo;
        private readonly IMapper mapper;

        public CreateBasicTraceabilityHandler(IBaseRepository<BasicTraceabilityModel> basicRepo,
                                              IMapper mapper)
        {
            this.basicRepo = basicRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(CreateBasicTraceabilityCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = basicRepo.GetAll().FirstOrDefault(x => x.Batch == request.Batch && !x.IsDel);
            if (res != null)
            {
                result.Message = "生产批次已存在!";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map<BasicTraceabilityModel>(request);
            model.CreateDate = DateTime.Now;
            model.CreateName = "张三";
            int r = basicRepo.AddAsync(model).Result;
            if (r > 0)
            {
                result.Message = "添加溯源基本信息成功";
                result.Data = r;
                result.Code = APIEnum.Ok;
            }
            else
            {
                result.Message = "添加溯源基本信息失败";
                result.Data = r;
                result.Code = APIEnum.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
